import React from 'react';
import {InputItem, List, NavBar, Icon} from 'antd-mobile';
import {connect} from 'react-redux';
import {getMsgList, sendMsg, recvMsg} from '../../redux/chat.redux';
import io from 'socket.io-client';
import { getChatId } from '../../util';
const socket = io('ws://localhost:9093');

@connect(
	state => state,
	{getMsgList, sendMsg, recvMsg}
)
export default class Chat extends React.Component{
	constructor(props) {
		super(props);
		this.state = {
			text: '',
			msg: [],
		}
	}
	componentDidMount() {		
		//2、监听到广播数据的事件，把数据存到state中
		// socket.on('recvMsg', (data) => {
		// 	this.setState({
		// 		msg: [...this.state.msg, data.text]
		// 	});
		// })
		if (!this.props.chat.chatmsg.length) {
			this.props.getMsgList();
			this.props.recvMsg();
		}
	}
	handleSubmit() {
		//1、首先触发一个sendMsg的事件，把前端输入的信息传递到后台
		// socket.emit('sendMsg', {text: this.state.text});
		// this.setState({text: ''});
		const from = this.props.user._id;
		const to = this.props.match.params.user;
		const msg = this.state.text;
		this.props.sendMsg({from, to, msg});
		this.setState({text: ''});
	}
	render() {
		const userid = this.props.match.params.user;
		const Item = List.Item;
		const users = this.props.chat.users;
		if (!users[userid]) {
			return null;
		}

		// 获取一组消息通信的唯一id
		const chatid = getChatId(userid, this.props.user._id);
		const chatmsgs = this.props.chat.chatmsg.filter(v => v.chatid === chatid);

		return(
			<div id="chat-page">
				<NavBar
					mode="dark"
					icon={<Icon type="left" />}
					onLeftClick={() => {
						this.props.history.goBack();
					}}
				>
					{ users[userid].name }
				</NavBar>
				{chatmsgs.map(v => {
					const avatar = require(`../img/${users[v.from].avatar}.png`);
					return v.from === userid ? (
						<List key={v._id}>
							<Item
								thumb={avatar}
							>{v.content}</Item>
						</List>
					) : (
						<List key={v._id}>
							<Item
								extra={<img alt="" src={avatar} />}
								className="chat-me"
							>{v.content}</Item>
						</List>
					)
				})}			
				<div className="stick-footer">
					<List>
						<InputItem
							placeholder="请输入"
							value={this.state.text}
							onChange={(v) => {this.setState({text: v})}}
							extra={<span onClick={()=>{this.handleSubmit()}}>发送</span>}
						>
						</InputItem>
					</List>
				</div>
			</div>
		)
	}
}